package cn.net.api;

/**本类用于测试顶级父类Object：重写toString()+hashCode()+equals()*/
import java.util.Objects;

//总结:
//1.如果想要查看对象的属性值,需要重写toString()
//  否则使用的就是Object的默认实现,打印的是对象的地址值
//2.如果要判断两个对象间的所有属性值相同,比较结果为true,就需要重写equals()
//  否则使用的就是Object的默认实现,通过==比较的是两个对象的地址值,不是属性
public class TestObject {
    public static void main(String[] args) {
            Student s =new Student();
            Student s2 = new Student("海绵宝宝",10);
            Student s3 = new Student("海绵宝宝",10);
        System.out.println(s);//Student{name='null', age=0};如果没有重写toString方法，打印的是地址值。
        System.out.println(s2);//Student{name='海绵宝宝', age=10}
        System.out.println(s.toString());//Student{name='null', age=0}
        System.out.println(s2.toString());//Student{name='海绵宝宝', age=10}

        System.out.println(s.hashCode());//961
        System.out.println(s2.hashCode());//1101528845

        System.out.println(s.equals(s2));//false
        System.out.println(s2.equals(s3));//true

    }

}
class Student{
    String name;
    int age;

    public Student() {//无参
        super();
    }

    public Student(String name, int age) {//全参
        this.name = name;
        this.age = age;
    }

    @Override //重写toString()
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override //重写equals(Object o)
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override //重写hashCode()
    public int hashCode() {
        return Objects.hash(name, age);
    }
}